<template>
  <div class="resource-property-data-editor">
    <div class="editor-header">
      <h3>资源属性数据编辑</h3>
      <div class="header-actions">
        <Button type="primary" @click="saveData" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存数据
        </Button>
        <Button @click="resetData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          重置数据
        </Button>
      </div>
    </div>

    <div class="editor-content">
      <!-- 数据加载状态 -->
      <div v-if="loading" class="loading-state">
        <Spin size="large" />
        <p>正在加载属性数据...</p>
      </div>

      <!-- 无Schema状态 -->
      <div v-else-if="!hasSchema" class="no-schema-state">
        <Icon
          icon="ant-design:exclamation-circle-outlined"
          class="warning-icon"
        />
        <p>该资源尚未配置属性结构，请先配置属性结构</p>
        <Button type="primary" @click="configureSchema">
          <IconifyIcon icon="ant-design:setting-outlined" />
          配置属性结构
        </Button>
      </div>

      <!-- 数据编辑器 -->
      <div v-else class="data-editor">
        <Tabs v-model:active-key="activeTab" class="editor-tabs">
          <!-- 表单编辑 -->
          <TabPane key="form" tab="表单编辑">
            <div class="form-editor">
              <!-- 原版表单 -->
              <div v-if="schemaType === 'manual'" class="manual-form">
                <Form
                  ref="formRef"
                  :model="formData"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  layout="horizontal"
                >
                  <FormItem
                    v-for="field in schemaFields"
                    :key="field.name"
                    :label="field.label"
                    :name="field.name"
                    :rules="getFieldRules(field)"
                  >
                    <!-- 文本输入 -->
                    <Input
                      v-if="field.type === 'TEXT'"
                      v-model:value="formData[field.name]"
                      :placeholder="
                        field.uiConfig?.placeholder || `请输入${field.label}`
                      "
                    />

                    <!-- 数字输入 -->
                    <InputNumber
                      v-else-if="field.type === 'NUMBER'"
                      v-model:value="formData[field.name]"
                      :placeholder="
                        field.uiConfig?.placeholder || `请输入${field.label}`
                      "
                      style="width: 100%"
                    />

                    <!-- 下拉选择 -->
                    <Select
                      v-else-if="field.type === 'SELECT'"
                      v-model:value="formData[field.name]"
                      :placeholder="
                        field.uiConfig?.placeholder || `请选择${field.label}`
                      "
                      style="width: 100%"
                    >
                      <SelectOption
                        v-for="option in field.options"
                        :key="option.value"
                        :value="option.value"
                      >
                        {{ option.label }}
                      </SelectOption>
                    </Select>

                    <!-- 布尔开关 -->
                    <Switch
                      v-else-if="field.type === 'BOOLEAN'"
                      v-model:checked="formData[field.name]"
                    />

                    <!-- 多行文本 -->
                    <Textarea
                      v-else-if="field.type === 'TEXTAREA'"
                      v-model:value="formData[field.name]"
                      :placeholder="
                        field.uiConfig?.placeholder || `请输入${field.label}`
                      "
                      :rows="4"
                    />

                    <!-- 默认文本输入 -->
                    <Input
                      v-else
                      v-model:value="formData[field.name]"
                      :placeholder="
                        field.uiConfig?.placeholder || `请输入${field.label}`
                      "
                    />
                  </FormItem>
                </Form>
              </div>

              <!-- useVbenForm版表单 -->
              <div
                v-else-if="schemaType === 'vbenform'"
                class="vbenform-editor"
              >
                <VbenForm
                  ref="vbenFormRef"
                  :schema="schemaData"
                  :options="schemaOptions"
                  :model="formData"
                  @submit="onFormSubmit"
                />
              </div>

              <!-- FormCreate版表单 -->
              <div
                v-else-if="schemaType === 'formcreate'"
                class="formcreate-editor"
              >
                <FormCreate
                  ref="formCreateRef"
                  :rule="schemaData.rules"
                  :option="schemaOptions"
                  :value="formData"
                  @submit="onFormSubmit"
                />
              </div>
            </div>
          </TabPane>

          <!-- JSON编辑 -->
          <TabPane key="json" tab="JSON编辑">
            <div class="json-editor">
              <div class="json-toolbar">
                <Button type="primary" @click="applyJsonChanges">
                  <IconifyIcon icon="ant-design:check-outlined" />
                  应用JSON
                </Button>
                <Button @click="formatJson">
                  <IconifyIcon icon="ant-design:format-painter-outlined" />
                  格式化
                </Button>
              </div>
              <Textarea
                v-model:value="jsonData"
                :rows="20"
                placeholder="请输入JSON格式的属性数据"
              />
            </div>
          </TabPane>

          <!-- 数据预览 -->
          <TabPane key="preview" tab="数据预览">
            <div class="data-preview">
              <div class="preview-toolbar">
                <Button type="primary" @click="refreshPreview">
                  <IconifyIcon icon="ant-design:reload-outlined" />
                  刷新预览
                </Button>
              </div>
              <div class="preview-content">
                <h4>当前数据</h4>
                <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
              </div>
            </div>
          </TabPane>
        </Tabs>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue';
import {
  Tabs,
  TabPane,
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  Select,
  SelectOption,
  Switch,
  Textarea,
  Spin,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import FormCreate from '@form-create/ant-design-vue';

// Props
const props = defineProps<{
  resource: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
  configureSchema: [];
}>();

// 响应式数据
const activeTab = ref('form');
const loading = ref(false);
const saving = ref(false);

// 表单相关
const formRef = ref();
const vbenFormRef = ref();
const formCreateRef = ref();

// Schema相关
const schemaData = ref(null);
const schemaOptions = ref({});
const schemaType = ref('');

// 表单数据
const formData = ref({});
const jsonData = ref('');

// 计算属性
const hasSchema = computed(() => {
  return schemaData.value && Object.keys(schemaData.value).length > 0;
});

const schemaFields = computed(() => {
  if (schemaType.value === 'manual' && schemaData.value?.fields) {
    return schemaData.value.fields;
  }
  return [];
});

// 获取字段验证规则
const getFieldRules = (field: any) => {
  const rules = [];

  if (field.required) {
    rules.push({
      required: true,
      message: `请${field.type === 'SELECT' ? '选择' : '输入'}${field.label}`,
      trigger: 'blur',
    });
  }

  if (field.validation) {
    if (field.validation.min !== undefined) {
      rules.push({
        min: field.validation.min,
        message: `${field.label}不能少于${field.validation.min}`,
      });
    }
    if (field.validation.max !== undefined) {
      rules.push({
        max: field.validation.max,
        message: `${field.label}不能超过${field.validation.max}`,
      });
    }
    if (field.validation.pattern) {
      rules.push({
        pattern: new RegExp(field.validation.pattern),
        message: `${field.label}格式不正确`,
      });
    }
  }

  return rules;
};

// 加载Schema
const loadSchema = async () => {
  loading.value = true;
  try {
    const response = await fetch(
      `/mock-api/resource-center/property-schema?resourceId=${props.resource.id}`,
    );
    if (response.ok) {
      const result = await response.json();
      if (result.data) {
        schemaData.value = result.data.schema;
        schemaOptions.value = result.data.options || {};
        schemaType.value = result.data.type;

        // 初始化表单数据
        initializeFormData();
      }
    }
  } catch (error) {
    console.error('加载Schema失败:', error);
    message.error('加载属性结构失败');
  } finally {
    loading.value = false;
  }
};

// 加载属性数据
const loadPropertyData = async () => {
  try {
    const response = await fetch(
      `/mock-api/resource-center/property-data?resourceId=${props.resource.id}`,
    );
    if (response.ok) {
      const result = await response.json();
      if (result.data) {
        formData.value = { ...result.data.data };
        jsonData.value = JSON.stringify(result.data.data, null, 2);
      }
    }
  } catch (error) {
    console.error('加载属性数据失败:', error);
  }
};

// 初始化表单数据
const initializeFormData = () => {
  if (schemaType.value === 'manual' && schemaData.value?.fields) {
    schemaData.value.fields.forEach((field: any) => {
      if (formData.value[field.name] === undefined) {
        formData.value[field.name] = field.defaultValue;
      }
    });
  }

  // 更新JSON数据
  jsonData.value = JSON.stringify(formData.value, null, 2);
};

// 保存数据
const saveData = async () => {
  saving.value = true;
  try {
    // 验证表单
    if (schemaType.value === 'manual') {
      await formRef.value?.validate();
    } else if (schemaType.value === 'vbenform') {
      const valid = await vbenFormRef.value?.validate();
      if (!valid) return;
    } else if (schemaType.value === 'formcreate') {
      const valid = await formCreateRef.value?.validate();
      if (!valid) return;
    }

    const data = {
      resourceId: props.resource.id,
      schemaId: schemaData.value?.id,
      data: formData.value,
    };

    const response = await fetch('/mock-api/resource-center/property-data', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });

    if (response.ok) {
      message.success('属性数据保存成功');
      emit('update', formData.value);
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    message.error('保存失败: ' + (error as Error).message);
  } finally {
    saving.value = false;
  }
};

// 重置数据
const resetData = () => {
  initializeFormData();
  message.success('数据已重置');
};

// 配置Schema
const configureSchema = () => {
  emit('configureSchema');
};

// 应用JSON变化
const applyJsonChanges = () => {
  try {
    const data = JSON.parse(jsonData.value);
    formData.value = data;
    message.success('JSON已应用');
  } catch (error) {
    message.error('JSON格式错误，请检查代码');
  }
};

// 格式化JSON
const formatJson = () => {
  try {
    const data = JSON.parse(jsonData.value);
    jsonData.value = JSON.stringify(data, null, 2);
    message.success('JSON已格式化');
  } catch (error) {
    message.error('JSON格式错误，无法格式化');
  }
};

// 刷新预览
const refreshPreview = () => {
  jsonData.value = JSON.stringify(formData.value, null, 2);
  message.success('预览已刷新');
};

// 表单提交回调
const onFormSubmit = (data: any) => {
  formData.value = data;
  message.success('表单数据已更新');
};

// 监听表单数据变化
watch(
  () => formData.value,
  () => {
    // 更新JSON数据
    jsonData.value = JSON.stringify(formData.value, null, 2);
  },
  { deep: true },
);

// 初始化
onMounted(async () => {
  await loadSchema();
  await loadPropertyData();
});
</script>

<style lang="less" scoped>
.resource-property-data-editor {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .editor-content {
    .loading-state {
      text-align: center;
      padding: 40px 20px;
      color: #8c8c8c;

      p {
        margin: 16px 0 0 0;
        font-size: 14px;
      }
    }

    .no-schema-state {
      text-align: center;
      padding: 40px 20px;
      color: #8c8c8c;

      .warning-icon {
        font-size: 48px;
        margin-bottom: 16px;
        color: #faad14;
      }

      p {
        margin: 0 0 16px 0;
        font-size: 14px;
      }
    }

    .data-editor {
      .editor-tabs {
        :deep(.ant-tabs-content) {
          padding: 16px 0;
        }
      }

      .form-editor {
        .manual-form {
          max-width: 600px;
        }

        .vbenform-editor,
        .formcreate-editor {
          max-width: 800px;
        }
      }

      .json-editor {
        .json-toolbar {
          margin-bottom: 16px;
          display: flex;
          gap: 8px;
        }

        .ant-input {
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          font-size: 12px;
          line-height: 1.5;
        }
      }

      .data-preview {
        .preview-toolbar {
          margin-bottom: 16px;
          display: flex;
          gap: 8px;
        }

        .preview-content {
          h4 {
            margin: 0 0 12px 0;
            color: #262626;
            font-size: 14px;
          }

          pre {
            background-color: #f5f5f5;
            padding: 12px;
            border-radius: 4px;
            font-size: 12px;
            color: #595959;
            margin: 0;
            overflow-x: auto;
            max-height: 400px;
            overflow-y: auto;
          }
        }
      }
    }
  }
}
</style>
